package net.easyjava.base.utils.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import net.easyjava.tools.http.HttpImageTools;
import net.easyjava.tools.http.bean.ImageBean;
import net.easyjava.tools.io.InputStreamTools;
import net.easyjava.tools.lang.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

/**
 * Created by wxnacy on 16/1/2.
 */
public class QiniuUploadUtils {
    private static Logger logger = LoggerFactory.getLogger(QiniuUploadUtils.class);
    private static final String ACCESS_KEY ="bCEBgE5HUwIZOgM8Ie5_LgoDXdPXQMHH9G_L3DDC";
    private static final String SECRET_KEY ="DFKffSri9hknn64wMPfn-ptKX_sYgc5inH6YE77R";

    private static final String BUCKET_EASYJAVA = "easyjava";
    private static final String BUCKET_ARTICLE_EASYJAVA = "article-easyjava";//存储文章
    private static final String BUCKET_IMG_EASYJAVA = "img-easyjava";

    private static final String HTTP_EASYJAVA = "http://7xppjg.com1.z0.glb.clouddn.com/";
    private static final String HTTP_ARTICLE_EASYJAVA = "http://7xq7o5.com1.z0.glb.clouddn.com/";//存储文章
    private static final String HTTP_IMG_EASYJAVA = "http://7xq7o2.com1.z0.glb.clouddn.com/";//图片

    private static final String CHARSET_UTF_8 = "utf-8";

    private static final long EXPIRES_PRIVATE_URL = 1000*60*60;//一个小时

    /**
     * 上传数据
     * @param data
     * @param key
     * @return
     */
    public static boolean upload(byte[] data,String key,String bucket){
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token = auth.uploadToken(bucket);
        UploadManager uploadManager = new UploadManager();
        try {
            Response response = uploadManager.put(data, key, token);//,null,"text/plain",true);
            if(response.isOK()){
                return true;
            }
            logger.error("七牛文件上传出错:"+response.error);
            return false;
        } catch (QiniuException e) {
            logger.error(e.response.toString());
            logger.error(e.getMessage(), e.fillInStackTrace());
            return false;
        }
    }

    /**
     * 上传文章
     * @param content
     * @return
     */
    public static String uploadArticle(String content){
        try {
            byte[] data = content.getBytes(Charset.defaultCharset());
            String key = StringTools.getRandomDir(4)+System.currentTimeMillis()+".txt";
            if(!upload(data,key,BUCKET_ARTICLE_EASYJAVA)){
                throw new Exception();
            }
            return HTTP_ARTICLE_EASYJAVA+key;
        } catch (Exception e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }

    /**
     * 上传图片
     * @param url
     * @return
     */
    public static String uploadImg(String url){
        try {
            ImageBean imageBean = HttpImageTools.getImageFromUrl(url);
            byte[] data = InputStreamTools.getByteByInputStream(imageBean.getInputStream());
            String key = StringTools.getRandomDir(4)+System.currentTimeMillis()+imageBean.getSuffix();
            if(!upload(data,key,BUCKET_IMG_EASYJAVA)){
                throw new Exception();
            }
            return HTTP_IMG_EASYJAVA+key;
        } catch (Exception e) {
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }

    /**
     * 获取私有空间真实地址
     * @param url
     * @return
     */
    public static String getPrivateUrl(String url){
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String token = auth.privateDownloadUrl(url,EXPIRES_PRIVATE_URL);
        return token;
    }

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();


        String url = "http://juheimg.oss-cn-hangzhou.aliyuncs.com/joke/201601/29/00B8CFB5FE8ABE1113B444FF74EC78C0.gif";// HTTP_ARTICLE_EASYJAVA+"2016/01/20/MOLB/1453294841326.txt";
        url = uploadImg(url);
        System.out.println("url = " + url);
//        String token = getPrivateUrl(url);
//        System.out.println("token = " + token);


        System.out.println("(System.currentTimeMillis()-begin) = " + (System.currentTimeMillis() - begin));
    }
}
